package com.artisan.springuitls.demos;

import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Comparator;
import java.util.Map;

/**
 * AntPathMatcher 工具类演示
 * 功能：路径匹配引擎
 * 优势：Spring MVC 路由底层引擎，支持 ? * ** 通配符，比正则更简洁
 */
@Component
public class AntPathMatcherDemo {

    private final AntPathMatcher matcher = new AntPathMatcher();

    /**
     * 场景：判断 URL 是否匹配 /api/user/**
     */
    public void matchUrl(String requestPath) {
        System.out.println("\n========== AntPathMatcher Demo ==========");
        
        // ✅ 通配符匹配
        boolean match = matcher.match("/api/user/**", requestPath);
        System.out.println("✓ 路径 '" + requestPath + "' 匹配 '/api/user/**': " + match);
    }

    /**
     * 演示基础匹配规则
     */
    public void demonstrateBasicMatching() {
        System.out.println("\n--- 基础匹配规则 ---");
        
        String path = "/api/user/1001/profile";
        
        // 1. 精确匹配
        System.out.println("✓ 精确匹配: " + 
            matcher.match("/api/user/1001/profile", path)); // true
        
        // 2. ? 匹配单个字符
        System.out.println("✓ ? 匹配单个字符: " + 
            matcher.match("/api/user/100?/profile", path)); // true
        
        // 3. * 匹配任意字符（不含 /）
        System.out.println("✓ * 匹配任意字符: " + 
            matcher.match("/api/user/*/profile", path)); // true
        
        // 4. ** 匹配任意层级路径
        System.out.println("✓ ** 匹配多层路径: " + 
            matcher.match("/api/**", path)); // true
        System.out.println("✓ ** 匹配任意后缀: " + 
            matcher.match("/api/user/**", path)); // true
        
        // 5. 后缀匹配
        System.out.println("✓ 后缀匹配 .html: " + 
            matcher.match("/**/*.html", "/pages/index.html")); // true
        
        System.out.println();
    }

    /**
     * 演示路径变量提取
     */
    public void demonstratePathVariableExtraction() {
        System.out.println("\n--- 路径变量提取 ---");
        
        String pattern = "/api/user/{id}/order/{orderId}";
        String path = "/api/user/1001/order/5001";
        
        // ✅ 提取路径变量
        Map<String, String> vars = matcher.extractUriTemplateVariables(pattern, path);
        System.out.println("✓ 提取的变量:");
        vars.forEach((key, value) -> 
            System.out.println("  - " + key + " = " + value));
        
        // 判断是否为模式（包含变量）
        System.out.println("✓ 是否为模式: " + matcher.isPattern(pattern)); // true
        System.out.println("✓ 普通路径是模式: " + matcher.isPattern(path)); // false
        
        System.out.println();
    }

    /**
     * 演示复杂模式匹配
     */
    public void demonstrateComplexPatterns() {
        System.out.println("\n--- 复杂模式匹配 ---");
        
        // 1. 多个通配符组合
        System.out.println("✓ 组合模式 '/api/*/user/**': " + 
            matcher.match("/api/*/user/**", "/api/v1/user/profile/avatar")); // true
        
        // 2. 可选路径段
        System.out.println("✓ 可选段 '/api/{version}/user': " + 
            matcher.match("/api/{version}/user", "/api/v2/user")); // true
        
        // 3. 文件扩展名匹配
        System.out.println("✓ 文件类型 '**/*.{jpg,png}': " + 
            matcher.match("**/*.{jpg,png}", "/images/logo.png")); // true
        System.out.println("✓ 文件类型 '**/*.{jpg,png}': " + 
            matcher.match("**/*.{jpg,png}", "/images/logo.gif")); // false
        
        // 4. 前缀匹配
        System.out.println("✓ 前缀匹配 '/api/**': " + 
            matcher.match("/api/**", "/api/v1/users")); // true
        
        System.out.println();
    }

    /**
     * 演示路径比较和排序
     */
    public void demonstratePathComparison() {
        System.out.println("\n--- 路径模式比较 ---");
        
        String path = "/api/user/1001";
        
        // 比较两个模式哪个更精确
        String pattern1 = "/api/user/*";
        String pattern2 = "/api/**";
        
        Comparator<String> comparator = matcher.getPatternComparator(path);
        int result = comparator.compare(pattern1, pattern2);
        
        System.out.println("✓ 对于路径 '" + path + "':");
        System.out.println("  - " + pattern1 + " vs " + pattern2);
        if (result < 0) {
            System.out.println("  - '" + pattern1 + "' 更精确");
        } else if (result > 0) {
            System.out.println("  - '" + pattern2 + "' 更精确");
        } else {
            System.out.println("  - 两者同样精确");
        }
        
        System.out.println();
    }

    /**
     * 演示路径合并
     */
    public void demonstratePathCombining() {
        System.out.println("\n--- 路径合并 ---");
        
        // 合并两个路径模式
        String combined1 = matcher.combine("/api", "/user/**");
        System.out.println("✓ 合并 '/api' + '/user/**' = " + combined1);
        
        String combined2 = matcher.combine("/api/**", "/user/profile");
        System.out.println("✓ 合并 '/api/**' + '/user/profile' = " + combined2);
        
        String combined3 = matcher.combine("/api/{version}", "/user/{id}");
        System.out.println("✓ 合并 '/api/{version}' + '/user/{id}' = " + combined3);
        
        System.out.println();
    }

    /**
     * 演示提取路径前缀
     */
    public void demonstratePathExtraction() {
        System.out.println("\n--- 路径提取 ---");
        
        String pattern = "/api/user/**";
        String path = "/api/user/1001/profile/avatar";
        
        // 提取匹配的路径部分
        String matchingPath = matcher.extractPathWithinPattern(pattern, path);
        System.out.println("✓ 模式: " + pattern);
        System.out.println("✓ 完整路径: " + path);
        System.out.println("✓ 提取的部分: " + matchingPath); // 1001/profile/avatar
        
        System.out.println();
    }

    /**
     * 实际应用场景：拦截器路径匹配
     */
    public void demonstrateInterceptorUsage() {
        System.out.println("\n--- 拦截器路径匹配场景 ---");
        
        // 定义拦截规则
        String[] includePatterns = {
            "/api/**",
            "/admin/**"
        };
        
        String[] excludePatterns = {
            "/api/public/**",
            "/admin/login"
        };
        
        // 测试请求路径
        String[] testPaths = {
            "/api/user/profile",
            "/api/public/config",
            "/admin/dashboard",
            "/admin/login",
            "/static/css/style.css"
        };
        
        System.out.println("✓ 拦截规则测试:");
        for (String path : testPaths) {
            boolean included = matchesAny(path, includePatterns);
            boolean excluded = matchesAny(path, excludePatterns);
            boolean shouldIntercept = included && !excluded;
            
            System.out.println("  - " + path + ": " + 
                (shouldIntercept ? "拦截" : "放行"));
        }
        
        System.out.println();
    }

    /**
     * 实际应用场景：微服务网关路由
     */
    public void demonstrateGatewayRouting() {
        System.out.println("\n--- 微服务网关路由场景 ---");
        
        // 定义路由规则
        Map<String, String> routes = Map.of(
            "/api/user/**", "user-service",
            "/api/order/**", "order-service",
            "/api/payment/**", "payment-service",
            "/admin/**", "admin-service"
        );
        
        // 测试路由
        String[] testPaths = {
            "/api/user/1001/profile",
            "/api/order/5001",
            "/api/payment/callback",
            "/admin/dashboard"
        };
        
        System.out.println("✓ 路由匹配结果:");
        for (String path : testPaths) {
            String matchedService = null;
            for (Map.Entry<String, String> route : routes.entrySet()) {
                if (matcher.match(route.getKey(), path)) {
                    matchedService = route.getValue();
                    break;
                }
            }
            System.out.println("  - " + path + " -> " + 
                (matchedService != null ? matchedService : "未找到服务"));
        }
        
        System.out.println("==========================================\n");
    }

    /**
     * 辅助方法：检查路径是否匹配任意模式
     */
    private boolean matchesAny(String path, String[] patterns) {
        for (String pattern : patterns) {
            if (matcher.match(pattern, path)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 最佳实践
     */
    public void printBestPractices() {
        System.out.println("\n========== 最佳实践 ==========");
        System.out.println("✓ 1. 通配符说明:");
        System.out.println("     ? - 匹配单个字符");
        System.out.println("     * - 匹配任意字符（不含 /）");
        System.out.println("     ** - 匹配任意层级路径");
        System.out.println("✓ 2. 路径变量使用 {name} 格式");
        System.out.println("✓ 3. 优先使用精确匹配，提升性能");
        System.out.println("✓ 4. 拦截器中缓存 AntPathMatcher 实例");
        System.out.println("✓ 5. 使用 getPatternComparator 排序规则");
        System.out.println("==========================================\n");
    }
}

